import { constantRoutes } from '@/router'
import { userMenu } from '@/api/user'
import Layout from '@/layout/index'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      // 先查询后台并返回左侧菜单数据并把数据添加到路由
      userMenu().then(response => {
        let data = response
        data = response.data
        var accessedRoutes = []
        generaMenu(accessedRoutes, data)
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      }).catch(error => {
        console.log(error)
      })
    })
  }
}
/**
 * 后台查询的菜单数据拼装成路由格式的数据
 * @param routes
 */
export function generaMenu(routes, data) {
  data.forEach(item => {
    const menu = {
      name: item.name,
      path: item.html_path.length === 0 ? '' : item.html_path,
      // component: item.component === '#' ? 'Layout' : loadView(item.component),
      component: item.html_view.length === 0 ? Layout : loadView(item.html_view),
      // redirect: item.redirect,
      // hidden: true,
      meta: { title: item.name },
      hidden: parseInt(item.is_show) === 0,

      children: [
        // {
        //   name: item.children.name,
        //   path: item.children.path,
        //   component: loadView(item.children.component),
        //   // hidden: true,
        //   meta: { title: item.children.meta.title, icon: item.children.meta.icon }
        // }
      ]
    }
    if (item.menuTwo) {
      generaMenu(menu.children, item.menuTwo)
    } else {
      true
    }
    routes.push(menu)
  })
}

export const loadView = (view) => { // 路由懒加载
  // return ()=>import(`@/views/${view}`)
  return (resolve) => require([`@/views${view}`], resolve)
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
